<?php

namespace App\Models\WorkOrder;

use App\Enums\WorkOrder\MissionEnum;
use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Collection;

class WorkOrderMissionModel extends BaseModel
{
    use KfSoftDeletes;
    use KfUid;

    protected $table = 'work_order_missions';

    protected $fillable = [
        'workOrderNo',
        'step',
        'dealUid',
        'missionStatus',
        'completeTime',
        'isDeleted',
    ];

    /**
     * 新增任务
     * @param string $workOrderNo
     * @param int $nextStep
     * @param int $dealUid
     * @return Builder|\Illuminate\Database\Eloquent\Model
     */
    public static function add(
        string $workOrderNo,
        int $nextStep,
        int $dealUid,
        int $missionStatus = MissionEnum::MISSION_STATUS_0
    ) {
        if ($missionStatus == MissionEnum::MISSION_STATUS_1) {
            $completeTime = time();
        } else {
            $completeTime = 0;
        }

        return WorkOrderMissionModel::query()->create([
            'workOrderNo'   => $workOrderNo,
            'step'          => $nextStep,
            'dealUid'       => $dealUid,
            'missionStatus' => $missionStatus,
            'completeTime'  => $completeTime,
        ]);
    }

    /**
     * 完成任务
     * @param string $workOrderNo
     * @param int $nowStep
     * @return int
     */
    public static function finish(string $workOrderNo, int $nowStep): int
    {
        return WorkOrderMissionModel::query()
                                    ->where('workOrderNo', $workOrderNo)
                                    ->where('step', $nowStep)
                                    ->update([
                                        'missionStatus' => MissionEnum::MISSION_STATUS_1,
                                        'completeTime'  => time()
                                    ]);
    }


    /**
     * 获取待处理任务
     *
     * @param string $workOrderNo
     * @return Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getStayMission(string $workOrderNo)
    {
        return self::query()
                   ->where("workOrderNo", $workOrderNo)
                   ->where("missionStatus", MissionEnum::MISSION_STATUS_0)
                   ->get();
    }


    public static function progressResolve(string $workOrderNo, array $progress)
    {
        $missionInfo = WorkOrderMissionModel::query()
                                            ->with([
                                                "applyManagerRel" => function ($query) use ($workOrderNo) {
                                                    $query->where("workOrderNo", $workOrderNo);
                                                }
                                            ])
                                            ->where("workOrderNo", $workOrderNo)
                                            ->whereIn("step", $progress)
                                            ->get();

        return $missionInfo->groupBy("step")
                           ->map(
                               function (Collection $v, $step) {

                                   return [
                                       "step"     => $step,
                                       "stepDesc" => MissionEnum::STEP_TEXT[$step],
                                       "handle"   => $v->map(function ($manager) {

                                           return [
                                               "id"            => $manager->applyManagerRel->id,
                                               "role"          => $manager->applyManagerRel->role ?? 0,
                                               "roleDesc"      => WorkOrderUserRoleModel::ROLE_TYPE_TEXT[$manager->applyManagerRel->role ?? 0] ?? '',
                                               "dealUid"       => $manager->dealUid,
                                               "missionStatus" => $manager->missionStatus,
                                               "completeTime"  => formatDate($manager->completeTime, ""),
                                               "managerName"   => $manager->applyManagerRel->managerName ?? '',
                                           ];
                                       })->values()->toArray()
                                   ];
                               });
    }

    /**
     * @return HasOne
     */
    public function applyManagerRel(): HasOne
    {
        return $this->hasOne(WorkOrderApplyManagerModel::class, "managerId", "dealUid");
    }

    /**
     * @return HasOne
     */
    public function applyMainRel(): HasOne
    {
        return $this->hasOne(WorkOrderApplyMainModel::class, "workOrderNo", "workOrderNo");
    }
}
